<?php
namespace Home\Controller;

class AvatarController extends \Home\Controller\BaseController
{
	/**
	 * 上传并设置用户头像
	 * @author 刘新
	 */
	public function uploadAvatar()
	{
		//用户头像的类型为50
		$fileType = 50;
		$param['fileType'] = $fileType;
	
		//获取文件上传者信息
		$param['operatorId'] = $this->user['userId'];
		$param['operatorName'] = $this->user['mobile'];
		$param['operatorType'] = 1;
	
		//设置上传驱动
		$fileDriver = C('DOWNLOAD_UPLOAD_DRIVER');
	
		//设置允许上传的头像类型
		$set = C('DOWNLOAD_UPLOAD');
		$set['exts'] = C('FILE_EXTS')[$fileType];
	
		//上传文件
		$file = D('File');
		$info = $file->upload($_FILES, $set, C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$fileDriver}_CONFIG"));

		//上传失败
		if(!$info) $this->ajaxReturn(array('error' => 1, 'info' => $file->getError()));

		//上传成功，更新User表
		$info = $info['download'];
		$data['id'] = $this->user['userId'];
		$data['avatar_id'] = $info['id'];
		$data['avatar_url'] = $info['url'];
		//更新数据
		$user = D('User');
		$res = $user->editUser($data);

		//更新失败
		if(!$res) {
			$this->errorLog(__FILE__, __LINE__, $user->getDbError() . '---' . $user->getError());
				
			//删除已上传的文件
			M('File')->where(array('id' => $info['id']))->delete();
			unlink($info['realpath']);
				
			//返回结果
			$this->ajaxReturn(array('error' => 1, 'info' => '头像更新失败'));
		}
	
		//更新成功
		$info = array('url' => $info['url'], 'avatar_id' => $info['id']);
		$this->ajaxReturn(array('error' => 0, 'info' => $info));
	}
}